import { FC, useMemo } from 'react';
import { useRequest } from 'ahooks';
import numeral from 'numeral';
import MobileStockItem from '@/components/mobile-stock-item';
import { getQtClist, getQtKlines } from '@/service/apis/east-money';
import { getTriggerRecords } from '@/service/apis/trigger-record';
import { formatKLineStrToKLineObj, formatSimpleInfosToInfoObj } from '@/utils/format';

const TriggerRecord: FC = () => {
  const { data: cList } = useRequest(getQtClist);

  const { data: qtList } = useRequest(() => getQtKlines('1.000001'));

  const date = useMemo(() => {
    const str = qtList?.klines?.at(-1);

    if (str) {
      const kline = formatKLineStrToKLineObj(str);

      return kline?.date;
    }

    return;
  }, [qtList]);
  //   const {} = useMemo(() => {

  //   }, [clist]);
  const { data }: any = useRequest(
    () => {
      if (date) {
        return getTriggerRecords({ triggerDate: date });
      }

      return Promise.resolve([]);
    },
    { refreshDeps: [date] },
  );

  const dataSource = useMemo(() => {
    const map = {};

    cList?.forEach((item) => {
      const kline = formatSimpleInfosToInfoObj(item);
      const { newest, code, PE, PB, TMV, VR, CMV, TYChg, PETTM } = kline;

      map[code] = {
        ...kline,
        pe: numeral(PE)?.format('0.00'),
        pb: numeral(PB)?.format('0.00'),
        tmv: numeral(TMV)?.format('0.00'),
        vr: numeral(VR)?.format('0.00'),
        cmv: numeral(CMV)?.format('0.00'),
        tyChg: numeral(TYChg)?.format('0.00'),
        pettm: numeral(PETTM)?.format('0.00'),

        date,
        close: newest,
      };
    });

    return data?.infos?.map((item) => {
      const kline = map[item.code];
      const lastKline = item?.klines?.at(-1);

      if (kline?.date !== lastKline?.date) {
        item?.klines.push(kline);
      }

      return item;
    });
  }, [cList, data, date]);

  return <>{dataSource?.map((item) => <MobileStockItem {...item} key={item?.code} />)}</>;
};

export default TriggerRecord;
